<?php

namespace App\Listeners;

use App\Events\WxMessagePush;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Utils\WxMessagePush as messagePush;
use App\Models\PushRecord;
use App\Contant\WxMessageType;
class MessagePushListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Handle the event.
     *
     * @param  name  $event
     * @return void
     */
    public function handle(WxMessagePush $event)
    {
        $data = $event->data;
        $openid = $data['openid'];
        $user = $data['user'];
        $courseClass = $data['message']['course'];
        if(!$openid){
            return false;
        }
        $wxPush = new messagePush();
        $res = $wxPush->sendMessage($data);
        $result = json_decode($res,true);
        logger()->info($res);
        $courseClass->is_push += 1;
        $pushRecord = PushRecord::where('user_id',$user->id)->where('course_class_id',$courseClass->id)->where('type', WxMessageType::CREATE)->first();
        if(!$pushRecord){
            $pushRecord = new PushRecord();
        }
        $pushRecord->user_id = $user->id;
        $pushRecord->course_class_id = $courseClass->id;
        $pushRecord->type = WxMessageType::CREATE;

        if($result['errcode'] == 0){
            $pushRecord->state = 1;
        }else{
            $pushRecord->state = 0;
        }
        $pushRecord->save();

    }
}
